package com.kaxicore.kaxi.serviceImpl;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.lang.Integer;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.kaxicore.kaxi.entity.Staff;
import com.kaxicore.kaxi.mapper.StaffMapper;
import com.kaxicore.kaxi.service.StaffService;
import com.kaxicore.kaxi.utils.PageRequest;
import com.kaxicore.kaxi.utils.PageResult;
import com.kaxicore.kaxi.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StaffServiceImpl implements StaffService {
    @Autowired
    private StaffMapper mapper;

    @Override
    public PageResult getAllStaffs(String name, PageRequest pageRequest) throws Exception {
        List<Staff> results = mapper.getAllStaffs(name);
        results.sort(Comparator.comparing(Staff::getStaffID).reversed());

        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        Page page = new Page(pageNum, pageSize);
        int total = results.size();
        page.setTotal(total);
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);

        if (startIndex > endIndex) {
            page.addAll(new ArrayList());
            PageInfo pageInfo = new PageInfo<>(page);
            return PageUtils.getPageResult(pageRequest,pageInfo);
        } else {
            page.addAll(results.subList(startIndex, endIndex));
            PageInfo pageInfo = new PageInfo<>(page);
            return PageUtils.getPageResult(pageRequest,pageInfo);
        }
    }

    @Override
    public Staff getStaffById(Integer id) throws Exception {
        return mapper.getStaffById(id);
    }

    @Override
    public void addStaff(Staff staff) throws Exception {
        mapper.addStaff(staff);
        return;
    }

    @Override
    public void deleteStaffById(Integer id) throws Exception {
        mapper.deleteStaff(id);
        return;
    }

    @Override
    public void updateStaff(Staff staff) throws Exception {
        mapper.updateStaff(staff);
        return;
    }

}
